package com.xiaoning.sun.spring.mvc.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xiaoning.sun.spring.mvc.controller.LoginController;
import com.xiaoning.sun.spring.mvc.utils.StringUtils;

/**
 * @author xiaoning.sun
 * @Date 2016年5月20日
 * @Description: 使用Interceptor实现登录页面过滤
 */
public class SessionInterceptor extends HandlerInterceptorAdapter{
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	public static final String[] IGNORE_URL={"index","login"};
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException{
		boolean flag = false;
		String requestURL = request.getRequestURI().toString();
		logger.info("request URL:" + requestURL);
		for(String url: IGNORE_URL){
			if(url.contains(url)){
				flag = true;
				break;
			}else{
				HttpSession session = request.getSession();
				String user = (String)session.getAttribute("userName");
				if(StringUtils.isEmpty(user)){
					response.sendRedirect("index.jsp");
				}
			}
		}
		return flag;
	}
}
